<template>
	<view class="container" :style="containHeight">
		<view class="content">
			<view class="search-content">
				<view class="search-item">
					<text class="search-label">题目类型：</text>
					<zxz-uni-data-select :localdata="typeBank" placeholder="请选择题目类型" v-model="searchParams.type"
						dataKey="label" dataValue="value" @change="isTypeConfirm">
					</zxz-uni-data-select>
					<!-- <u-picker :show="isType" :columns="typeOptions" v-model="searchParams.type" @confirm="isTypeConfirm"
						@cancel="isType=false" keyName="label"></u-picker>
					<view class="select-border" @click="isType=true">
						<text v-if="!searchParams.type">请选择题目类型</text>
						<text v-if="searchParams.type" class="selectedTxt">{{searchParams.type}}</text>
					</view> -->
				</view>
				<view class="search-item">
					<text class="search-label">关键字：</text>
					<u--input placeholder="请输入关键字" v-model="searchParams.stem"></u--input>
				</view>
				<view class="btn-group">
					<u-button text="查询" type="primary" :loading="btnSearch" loadingText="查询中" class="search-btn"
						@click="toSearch"></u-button>
				</view>
			</view>
			<view v-if="editList.length==0">
				<u-empty mode="list" icon="../../static/listEmpty.png"></u-empty>
			</view>
			<u-swipe-action v-for="(item,index) in editList" :key="index" autoClose v-else>
				<u-swipe-action-item :options="optionsEdit" @click="swipeItem(item,$event)">
					<view class="historicalAchievements_item u-border-bottom">
						<text class="bold">题目类型：</text>
						<text v-if="item.type ==1">单选题</text>
						<text v-if="item.type ==2">多选题</text>
						<text v-if="item.type ==3">判断题</text>
						<view>
							<text class="bold">题干：</text>
							<text>{{item.stem}}</text>
						</view>
						<u-row>
							<u-col span="1.5">
								<text class="bold">选项：</text>
							</u-col>
							<u-col span="10.5">
								<text v-for="(val,key,i) in item.options" :key="i"
									class="layout-start">{{key+'：'+val+' '}} </text>
							</u-col>
						</u-row>
						<view>
							<text class="bold">答案：</text>
							<text v-for="(itm,indx) in item.correctOptions" :key="indx">
								<text v-if="indx">,</text>{{itm}}
							</text>
						</view>
						<view v-if="item.analysis">
							<text class="bold">解析：</text>
							<text>{{item.analysis}}</text>
						</view>
					</view>

				</u-swipe-action-item>
			</u-swipe-action>
			<u-loadmore :status="statusLoading" v-if="editList.length!=0" />
		</view>
		<u-popup :show="isNewEdit" showCancelButton @close="cancelEdit('uForm')" mode="center"
			:overlayStyle="{'touch-action':'none'}" class="dialog">
			<view class="scroll">
				<view class="popupTitle">编辑试题</view>
				<u--form labelPosition="left" :model="formDialog" :rules="rules" ref="uForm">
					<u-form-item label="题目类型" prop="type" required>
						<view class="select-border" @click="isModalType=true">
							<text v-if="!formDialog.type">请选择题目类型</text>
							<text v-if="formDialog.type" class="selectedTxt">{{formDialog.type}}</text>
						</view>
					</u-form-item>
					<u-form-item label="题干" prop="stem" required>
						<u--textarea v-model="formDialog.stem" placeholder="请输入题干"></u--textarea>
					</u-form-item>
					<u-form-item label="选项" prop="options">
						<u-button text="新增" type="primary" @click="onAddOptions()"></u-button>
					</u-form-item>
					<u-row>
						<u-col span="10" offset="1.6">
							<u--input placeholder="请输入内容" v-for="(val, key, i) in formDialog.options" :key="i"
								v-model="formDialog.options[key]" style="margin-bottom: 20rpx;">
								<u--text :text="key" slot="prefix" margin="0 3px 0 0" type="tips"></u--text>
								<template slot="suffix">
									<view @click="onDelOptions(key, val)">
										<u-icon name="close"></u-icon>
									</view>
								</template>
							</u--input>
						</u-col>
					</u-row>
					<u-form-item label="正确答案" prop="correctOptions">
						<view v-if="formDialog.type == '单选题' || formDialog.type == '判断题'">
							<u-radio-group v-model="formDialog.correctOptions" placement="column">
								<u-radio :customStyle="{marginBottom: '8px'}"
									v-for="(rval, rkey, i) in formDialog.options" :key="'r-' + i" :label="rkey"
									:name="rkey">
								</u-radio>
							</u-radio-group>
						</view>
						<view v-if="formDialog.type == '多选题'">
							<u-checkbox-group v-model="formDialog.correctOptions" placement="column">
								<u-checkbox :customStyle="{marginBottom: '8px'}"
									v-for="(cval, ckey, i) in formDialog.options" :key="'c-' + i" :label="ckey"
									:name="ckey">
								</u-checkbox>
							</u-checkbox-group>
						</view>
					</u-form-item>
					<u-form-item label="解析" prop="analysis" class="mB80">
						<u--textarea v-model="formDialog.analysis" placeholder="请输入解析"></u--textarea>
					</u-form-item>
				</u--form>
				<view class="btn-group absolutePosition">
					<u-button text="取消" class="reset-btn" @click="cancelEdit('uForm')"></u-button>
					<u-button text="确认" type="primary" class="search-btn" @click="confirmEdit('uForm')"></u-button>
				</view>
				<u-picker :show="isModalType" :columns="typeOptions" v-model="formDialog.type"
					@confirm="isModalTypeConfirm" @cancel="isModalType=false" keyName="label"
					class="form-picker"></u-picker>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		challengeResult,
		selectDeptName,
		challengeResultSelect,
		viewQuestionBank,
		delQuestion,
		selectQuestion,
		updateQuestion
	} from "../../utils/api.js"
	export default {
		data() {
			return {
				fullHeight: true,
				editList: [],
				total: null, //总条数
				page: 1, //当前页码
				pageSize: 5, //每页显示数量
				userId: null,
				isType: false,
				typeOptions: [
					[{
							value: 1,
							label: "单选题",
						},
						{
							value: 2,
							label: "多选题",
						},
						{
							value: 3,
							label: "判断题",
						},
					]
				],
				typeBank: [{
						value: 1,
						label: "单选题",
					},
					{
						value: 2,
						label: "多选题",
					},
					{
						value: 3,
						label: "判断题",
					},
				],
				searchParams: {
					type: '',
					stem: '',
				},
				btnSearch: false,
				//仅用于像后端传递数据
				paramsValue: {
					questionBankId: '',
					stem: '',
					type: '',
					pageSize: 5,
					page: 1,
				},
				statusLoading: 'loadmore',
				nextQuery: false,
				onlyReachBottom: true,
				questionBankId: '',
				optionsEdit: [{
					text: '编辑',
					style: {
						backgroundColor: '#3c9cff'
					}
				}, {
					text: '删除',
					style: {
						backgroundColor: '#f56c6c'
					}
				}],
				isNewEdit: false,
				formDialog: {
					id: "",
					stem: "",
					options: {},
					correctOptions: [],
					analysis: "",
					type: "",
					questionBankId: "",
					status: 0,
				},
				rules: {
					type: [{
						required: true,
						message: "请选择题目类型",
						trigger: "change"
					}, ],
					stem: [{
						required: true,
						message: "请输入题干",
						trigger: "blur"
					}],
				},
				isModalType: false,
			}
		},
		onLoad(option) {
			// console.log("questionBankId option", option.questionBankId);
			this.questionBankId = option.questionBankId
			// this.userId = uni.getStorageSync('userinfo').id
			this.getEditList()
			// this.getOptions()
		},
		onReachBottom() {
			if (this.fullHeight) {
				this.fullHeight = false
			}
			if (this.nextQuery) {
				//搜索结果
				++this.paramsValue.page
				this.btnSearch = false
				//处理参数向后端查询数据
				this.paramsValue.type = this.searchParams.type
				this.paramsValue.stem = this.searchParams.stem
				this.paramsValue.questionBankId = this.questionBankId
				//过滤空的参数
				const params = Object.keys(this.paramsValue).filter((key) => this.paramsValue[key] !== null && this
					.paramsValue[key] !== '' && this.paramsValue[key] !== undefined).reduce((acc, key) => ({
					...acc,
					[key]: this.paramsValue[key]
				}), {})
				// console.log("const params", params);
				selectQuestion(
					params
				).then(s => {
					// console.log("查询s", s);
					if (s.code === 20000) {
						this.editList = this.editList.concat(s.data.records)
						// console.log("this.editList onreachbooon 查询", this.editList);
						this.onlyReachBottom = false
						//所有数据加载完
						if (s.data.total == this.editList.length) {
							this.statusLoading = 'nomore'
							this.nextQuery = false
							// console.log("s.data.total==this.editList.length");
						}
					} else {
						uni.showToast({
							title: s.message,
							icon: 'none'
						})
					}
				})
			} else if (this.onlyReachBottom) {
				// console.log("this.page * this.pageSize < this.total", this.page * this.pageSize < this.total);
				// console.log("1", this.page, this.pageSize, this.total);
				if (this.page * this.pageSize < this.total) {
					this.statusLoading = 'loading'
					this.page++
					this.getEditList()
					console.log("onReachBottom");
				} else {
					this.statusLoading = 'nomore'

				}
			} else {
				console.log("什么也不做");
			}
		},
		computed: {
			containHeight() {
				return this.fullHeight ? {
					height: 'calc(100vh - 44px)'
				} : {
					height: '100%'
				}
			},
		},
		// onShow() {
		// 	this.fullHeight = true
		// },
		methods: {
			getEditList(isdel) {
				viewQuestionBank({
					questionBankId: this.questionBankId,
					pageSize: this.pageSize,
					page: this.page,
				}).then(s => {
					if (s.code === 20000) {
						console.log("isdel", isdel, "isdel==ture", isdel == 'ture');
						if (isdel == 'ture') {
							//删除操作
							this.editList = s.data.records
						} else {
							this.editList = this.editList.concat(s.data.records)
						}
						// this.editList = this.editList.concat(s.data.records)
						// this.editList = s.data.records
						this.total = s.data.total
						if (this.total < this.pageSize) {
							this.statusLoading = 'nomore'
						}
					} else {
						uni.showToast({
							title: s.message,
							icon: "none"
						})
					}
				})
			},
			toSearch() {
				this.paramsValue.page = 1
				this.btnSearch = true
				this.onlyReachBottom = false
				//处理参数向后端查询数据							
				this.paramsValue.type = this.searchParams.type
				this.paramsValue.stem = this.searchParams.stem
				this.paramsValue.questionBankId = this.questionBankId
				//过滤空的参数
				const params = Object.keys(this.paramsValue).filter((key) => this.paramsValue[key] !== null && this
					.paramsValue[key] !== '' && this.paramsValue[key] !== undefined).reduce((acc, key) => ({
					...acc,
					[key]: this.paramsValue[key]
				}), {})
				console.log("const params", params);
				this.editList = []
				selectQuestion(
					params
				).then(s => {
					console.log("查询s", s);
					if (s.code === 20000) {
						//搜索结果反映到视图
						this.btnSearch = false
						this.editList = s.data.records
						this.nextQuery = true
						// this.searchList = this.searchList.concat(s.data.data)
						//查询结果的页数,向上取整
						let searchPageNum = Math.ceil(s.data.total / this.pageSize)
						this.page = 1
						if (searchPageNum > this.page) {
							//调查询接口，页码加1							
							this.statusLoading = 'loading'
							console.log("还有下一页");
						} else {
							this.statusLoading = 'nomore'
							console.log("只有当前页");
						}

					} else {
						uni.showToast({
							title: s.message,
							icon: 'none'
						})
					}
				})
			},
			isTypeConfirm(val) {
				// this.isType = false
				// this.searchParams.type = val.value[0].label
			},
			swipeItem(item, e) {
				// console.log("swipeItem e", e);
				// console.log("item", item);
				if (e.index == 0) {
					//编辑
					this.isNewEdit = true
					for (let key in item) {
						if (item.type == 1) {
							item.type = '单选题'
						} else if (item.type == 2) {
							item.type = '多选题'
						} else if (item.type == 3) {
							item.type = '判断题'
						} else {}
					}
					this.formDialog = item
					// 单选、判断- 拿到数组转字符串
					if (this.formDialog.type == '单选题' || this.formDialog.type == '判断题') {
						this.formDialog.correctOptions = this.formDialog.correctOptions[0];
					}
					console.log("this.formDialog", this.formDialog);
				} else if (e.index == 1) {
					//删除
					let that = this
					uni.showModal({
						title: '提示',
						content: '此操作将永久删除该题目, 是否继续?',
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
								delQuestion({
									id: item.id
								}).then(s => {
									if (s.code === 20000) {
										uni.showToast({
											title: '删除成功',
											icon: 'success'
										})
										that.getEditList('ture')
										that.$forceUpdate()
									} else {
										uni.showToast({
											title: s.message,
											icon: 'none'
										})
									}
								})
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});


				} else {

				}
			},
			confirmEdit(formName) {
				this.$refs[formName].validate().then(res => {					
					// let length = Object.keys(this.formDialog.options).length;
					this.limitLength()
					// uni.$u.toast('校验通过')
					// this.validSubmit()
					// if (this.formDialog.type == '判断题' && length !== 2) {
					// 	this.$message.error("判断题只能设置两个选项");
					// } else {
					// 	this.validSubmit();
					// }
				}).catch(errors => {
					uni.$u.toast('校验失败')
				})
			},
			// 限制选项的长度
			limitLength() {
				let optsLength = Object.keys(this.formDialog.options).length;
				let cursLength = this.formDialog.correctOptions.length;
				// console.log("optsLength", optsLength);
				// console.log("cursLength", cursLength);
				if (this.formDialog.type == '单选题') {
					if (optsLength < 2) {
						uni.$u.toast('单选题最少设置2个选项')
					} else if (optsLength > 5) {
						uni.$u.toast('单选题最多设置5个选项')
					} else if (cursLength == 0) {
						uni.$u.toast('请选择正确选项')
					} else {
						this.validSubmit();
					}
				} else if (this.formDialog.type == '多选题') {
					if (optsLength < 3) {
						uni.$u.toast('多选题最少设置3个选项')
					} else if (optsLength > 5) {
						uni.$u.toast('多选题最多设置5个选项')
					} else if (cursLength < 2) {
						uni.$u.toast('请至少设置两个正确选项')
					} else {
						this.validSubmit();
					}
				} else if (this.formDialog.type == '判断题') {
					if (optsLength !== 2) {
						uni.$u.toast('判断题只能设置两个选项')
					} else if (cursLength == 0) {
						uni.$u.toast('请选择正确选项')
					} else {
						this.validSubmit();
					}
				}
			},
			cancelEdit(formName) {
				this.isNewEdit = false
				this.$refs[formName].resetFields()
			},
			isModalTypeConfirm(val) {
				// console.log("val",val);
				this.isModalType = false
				this.formDialog.type = val.value[0].label
				// console.log("this.formDialog.type",this.formDialog.type);
			},
			// 新增选项
			onAddOptions() {
				const az = [...Array(5).keys()].map((i) => String.fromCharCode(i + 65)); //A-Z
				const last = Object.keys(this.formDialog.options).pop();
				let next = az[az.indexOf(last) + 1];
				if(next){
					this.$set(this.formDialog.options, next, "");
				}				
				// console.log("this.formDialog.options", this.formDialog.options);
			},
			// 删除选项
			onDelOptions(key, val) {
				// 直接删除当前选项
				let obj = JSON.parse(JSON.stringify(this.formDialog.options));
				delete obj[key];
				// 重新排序
				const az = [...Array(26).keys()].map((i) => String.fromCharCode(i + 65)); //A-Z
				let values = Object.values(obj);
				let orderObj = {};
				values.forEach((item, index) => {
					orderObj[az[index]] = item;
				});
				this.formDialog.options = orderObj;
			},
			// 正确的提交
			validSubmit() {
				if (this.formDialog.type == '单选题' || this.formDialog.type == '判断题') {
					let arr = [];
					arr.push(this.formDialog.correctOptions);
					this.formDialog.correctOptions = arr;
				}
				if (this.formDialog.type == '单选题') {
					this.formDialog.type = 1
				} else if (this.formDialog.type == '多选题') {
					this.formDialog.type = 2
				} else if (this.formDialog.type == '判断题') {
					this.formDialog.type = 3
				} else {}
				updateQuestion({
					id: this.formDialog.id,
					questionBankId: this.formDialog.questionBankId,
					type: this.formDialog.type,
					stem: this.formDialog.stem,
					options: this.formDialog.options,
					correctOptions: this.formDialog.correctOptions,
					analysis: this.formDialog.analysis,
				}).then(s => {
					if (s.code === 20000) {
						uni.showToast({
							title: '更新成功',
							icon: "success"
						})
						this.isNewEdit = false
						this.getEditList()
					} else {
						uni.showToast({
							title: s.message,
							icon: "none"
						})
					}
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		// background: url("../../static/bg.png");
		// background-size: cover;	
		background: linear-gradient(#5191FF 5%, #6AA2FF 8%, #BDD7FE 15%, #F6FAFF 100%);
		padding: 30rpx 30rpx;
		width: 100%;
		position: relative;
		box-sizing: border-box;

		.content {
			background: #ffffff;
			// margin-top: 30rpx;
			padding: 30rpx 32rpx 2rpx;
			box-sizing: border-box;
			border-radius: 15rpx;
			opacity: 0.9;
			width: 100%;
			position: relative;
		}
	}

	.medal {
		width: 50rpx;
		height: 50rpx;
		margin-left: 20rpx;
	}

	.historicalAchievements_item {
		background: #ffffff;
		box-sizing: border-box;
		padding: 30rpx;
		// margin: 40rpx 0rpx;
		// border-radius: 20rpx;
		// box-shadow: 4px 4px 10px #888888;

		.testPaperTitle {
			font-size: 28rpx;
			color: #000000;
			font-weight: bold;
		}

		.testTime {
			font-size: 28rpx;
			color: #737375;
			margin-top: 10rpx;
		}

		.line {
			height: 1rpx;
			background: #737375;
			width: 100%;
			margin: 30rpx 0rpx;
		}

		.historical_content {
			.historical_item {
				width: 100%;
				display: flex;
				justify-content: space-between;

				.historical_title {
					font-size: 30rpx;
					color: #737375;
				}

				.historical_txt {
					margin-top: 10rpx;
					font-size: 30rpx;
					color: #0B0B0B;
				}

				.bule {
					color: #3888FF;
					font-size: 32rpx;
				}
			}
		}
	}

	.warnTxt {
		color: #E13124 !important;
		font-size: 30rpx !important;
	}

	.search-content {
		box-sizing: border-box;
		padding: 0rpx 15rpx;
		width: 100%;
		position: relative;
		background: #ffffff;

		.search-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			width: 100%;
			margin-top: 10rpx;
			font-size: 30rpx;
			box-sizing: border-box;
			padding: 10rpx 20rpx;

			.select-border-has {
				width: 80%;
				height: 38px;
				line-height: 38px;
				border: 1px solid #dadbde;
				border-radius: 50rpx;
				// color: #B1B1B1;
				box-sizing: border-box;
				padding: 0rpx 25rpx;
				font-size: 16px;
				// z-index: 9;
				position: relative;
				display: flex;
				align-items: center;

				.selectedTxt {
					color: rgb(48, 49, 51);
				}
			}
		}

		.search-label {
			max-width: 300rpx;
			overflow: hidden;
			// text-overflow: ellipsis;
			white-space: nowrap;
			font-size: 30rpx;
		}


	}

	.btn-group {
		display: flex;
		margin-top: 60rpx;
		width: 100%;
		position: relative;
		justify-content: space-between;

		.search-btn {
			width: 40%;
			border-radius: 100rpx;
			background: linear-gradient(to right, #7774ff, #017ffd, #01b1fd);
			color: #fff;
		}

		.reset-btn {
			width: 40%;
			border-radius: 100rpx;
		}
	}

	.dateBorder {
		width: 80%;
		height: 38px;
		border: 1px solid #dadbde;
		border-radius: 50rpx;
		box-sizing: border-box;
		padding: 0rpx 25rpx;
		font-size: 16px;
		z-index: 1;
	}

	.bold {
		font-weight: 700;
		white-space: nowrap;
		line-height: 1.6;
	}

	.select-border {
		width: 80%;
		height: 38px;
		line-height: 38px;
		border: 1px solid #dadbde;
		border-radius: 50rpx;
		color: #B1B1B1;
		box-sizing: border-box;
		padding: 0rpx 25rpx;
		font-size: 16px;
		// z-index: 0;

		.selectedTxt {
			color: rgb(48, 49, 51);
		}
	}


	/deep/.u-form-item__body__left__content__label {
		// white-space: nowrap;
	}

	// /deep/.u-modal__content{
	// 	overflow: auto;
	// }
	/deep/.u-popup__content {
		width: 90%;
		position: relative;
		padding: 40rpx;
		box-sizing: border-box;
		overflow: auto;
	}

	.scroll {
		height: 1200rpx; // 固定高度
		overflow-y: scroll; // 超出滚动
		overscroll-behavior: none; // 禁止滚动溢出
	}

	.popupTitle {
		font-weight: 900;
		white-space: nowrap;
		line-height: 1.6;
		text-align: center;
		position: -webkit-sticky;
		position: sticky;
		top: 0;
		z-index: 2;
		background: #ffffff;

	}

	.absolutePosition {
		position: absolute;
		bottom: 0;
		left: 0;
		width: 100%;
		background-color: #ffffff;
		margin: 0rpx 0rpx 20rpx 0rpx;
		box-sizing: border-box;
		padding-top: 20rpx;
	}

	.mB80 {
		margin-bottom: 80rpx;
	}

	/deep/.u-input[data-v-fdbb9fe6] {
		max-width: 68%;
		max-height: 38rpx;
	}

	/deep/.u-swipe-action-item__right {
		position: absolute;
		top: 1px;
		bottom: 1px;
		right: 1px;
	}

	.dialog {
		/deep/.u-popup__content {
			width: 90%;
			position: relative;
			padding: 40rpx;
			box-sizing: border-box;
			overflow: auto;
		}
	}
	.form-picker {
		/deep/.u-popup__content {
			width: 100%;
			padding: 0;
		}
	}
</style>